package heven.holt.wan.android.fragment

import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.annotation.SuppressLint
import android.graphics.drawable.AnimatedVectorDrawable
import android.graphics.drawable.AnimationDrawable
import android.os.Build
import android.os.Bundle
import android.view.*
import android.view.animation.*
import android.widget.ImageView
import androidx.annotation.RequiresApi
import androidx.navigation.findNavController
import heven.holt.library.base.BaseFragment
import heven.holt.library.extensions.getScreenWidth
import heven.holt.library.loading.extensions.setLoadingStateCommonDecorHeader
import heven.holt.wan.android.R
import heven.holt.wan.android.databinding.FragmentCustomAnimationBinding
import heven.holt.wan.android.loading.delegate.CommonTitleDelegate
import kotlin.math.hypot

class CustomAnimationFragment : BaseFragment<FragmentCustomAnimationBinding>() {
    override fun createDecorationView(): View {
        val commonTitleDelegate = CommonTitleDelegate(
            getString(R.string.title_custom_animation)
        ) { view ->
            val direction = MyCoinFragmentDirections.actionMyCoinFragmentToCoinRankFragment()
            view.findNavController().navigate(direction)
        }
        val loadingStateView =
            binding.root.setLoadingStateCommonDecorHeader(commonTitleDelegate)
        return loadingStateView.decorView
    }

    override fun bindViewBinding(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): FragmentCustomAnimationBinding =
        FragmentCustomAnimationBinding.inflate(inflater, container, false)

    private var cx = 0f
    private var cy = 0f

    @SuppressLint("ClickableViewAccessibility")
    override fun initView() {
        binding.imageView.setOnTouchListener { v, event ->
            if (event.action == MotionEvent.ACTION_DOWN) {
                cx = event.x
                cy = event.y
            }
            return@setOnTouchListener false
        }
    }

    override fun initData() {
        binding.handlers = Handlers()
    }

    inner class Handlers {
        fun startAnimation(view: View) {
            ((view as ImageView).drawable as AnimationDrawable).start()
        }

        fun startVectorAnimation(view: View) {
            ((view as ImageView).drawable as AnimatedVectorDrawable).start()
        }

        fun startViewPropertyAnimation(view: View) {
            view.animate()
                .alpha(0f)
                .setDuration(2000L)
                .setListener(object : AnimatorListenerAdapter() {
                    override fun onAnimationEnd(animation: Animator?) {
                        view.visibility = View.GONE
                    }
                })
        }

        @SuppressLint("ClickableViewAccessibility")
        fun startCircularRevealAnimation(view: View) {
            val finalRadius = hypot(cx.toDouble(), cy.toDouble()).toFloat()
            val animation =
                ViewAnimationUtils.createCircularReveal(
                    view, cx.toInt(),
                    cy.toInt(), 0f, finalRadius * 2
                )
            animation.duration = 3000
            animation.start()
        }

        @RequiresApi(Build.VERSION_CODES.LOLLIPOP_MR1)
        fun startAnimationWithInterpolator(view: View, index: Int) {
            val screenWidth = view.context.getScreenWidth()
            val isStart = view.x <= 0f
            val interpolator = when (index) {
                0 -> LinearInterpolator() //线性插值，其变化速率恒定
                1 -> AccelerateInterpolator(1f) //加速度插值，其变化开始速率较慢，后面加速,factor越大，起始速度越慢，但是速度越来越快
                2 -> DecelerateInterpolator(1f) //减速度插值，factor越大，起始速度越快，但是速度越来越慢
                3 -> AccelerateDecelerateInterpolator() //先加速后减速，其变化开始和结束速率较慢，中间加速
                4 -> AnticipateInterpolator(1f) //其变化开始向后甩，然后向前，tension的偏移越大，而且速度越快
                5 -> OvershootInterpolator(1f) //其变化开始向前甩，冲过目标值，tension越大，结束时的偏移越大，而且速度越快
                6 -> AnticipateOvershootInterpolator(1f) //结合4,5的插值器
                7 -> BounceInterpolator() //弹跳插值器,其变化在结束时反弹
                8 -> CycleInterpolator(1f) //循环插值器，cycles循环次数，动画反复执行，从而达到一个动画左右、垂直或者其他如斜方向上的反复弹动（摆动）
                else -> LinearInterpolator()
            }
            view.animate().translationX((if (isStart) screenWidth - view.width else 0).toFloat())
                .setInterpolator(interpolator)
                .setDuration(2000L)
                .setListener(null)
        }
    }

}